<template>
  <div class="login-container">
    <div class="main">
    <h4 class="title">博客后台</h4>
    <div class="login">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" @keyup.enter.native="login(ruleForm.username,ruleForm.password)">
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login(ruleForm.username,ruleForm.password)">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    </div>

  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'))
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        password: [{ validator: validatePass, trigger: 'blur' }],
        username: [{ validator: checkUsername, trigger: 'blur' }]
      }
    }
  },
  methods: {
    async login (username, password) {
      const { data: res } = await this.$api.userLogin({
        username,
        password
      })
      console.log(res)
      if (res.err_code === 0) {
        localStorage.setItem('username', res.data.username)
        localStorage.setItem('_id', res.data._id)
        localStorage.setItem('token', JSON.stringify(res.token))
        // 刷新 更新localstorage
        // window.location.reload()
        this.$router.push('/system/home')
      } else {
        localStorage.removeItem('username')
        localStorage.removeItem('_id')
        localStorage.removeItem('token')
        alert('请检查账号和密码是否正确')
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.login-container{
  width: 100%;
  height: 100%;
  background-color: #35495e;
}

.main {
  position: absolute;
  width: 500px;
  height: 265px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.main .title {
  color: #e1e1e1;
  font-weight: bold;
  font-size: 22px;
  text-align: center;
  margin-bottom: 20px;
}
.login {
  background: #fff;
  width: 500px;
  height: 220px;
  box-shadow: 0px 0px 3px 1px #e1e1e1;
  border-top: 2px solid #1c5de7;
  box-sizing: border-box;
  padding: 20px;
}
</style>
